package com.my.filter;

import com.my.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
// @WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1.获取请求url
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse  resp = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        StringBuffer url = req.getRequestURL();

        log.info("线程:{}",Thread.currentThread().getName());
        log.info("uri:{}", uri);   // /  login 路径
        // 2.判断请求url中是否包含login,如果包含，说明是登录操作放行。
        log.info("url:{}",url.toString()); // http://localhost:8080/login协议+全域名+路径
        // 3.获取请求头的token.
        if(uri.contains("login")){
            // 登录操作放行
            chain.doFilter(request,response);
            // 【注意】结束当前请求,否则令牌不存在，就会进入死循环
            return;
        }
        log.info("XXXXXXXXXXXXXXX");

       // 4.判断令牌是否存在 不存在报 401
        String token = req.getHeader("token");
        if(token == null){
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            log.info("令牌 is null");
//            throw new RuntimeException("未登录！");
            // 【注意】结束当前请求,否则令牌不存在，就会进入死循环
            return;
        }
        //5. 解析token,如果解析失败，响应401 [未授权]  400[参数有问题] 405[请求方法有问题]

        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("claims:{}",claims);
        } catch (Exception e) {
            resp.setStatus(401);
            log.info("令牌解析失败！");
//            throw new RuntimeException("未登录，请先登录");
            // 【注意】结束当前请求,否则令牌不存在，就会进入死循环
            return;
        }
//        6. 放行
        chain.doFilter(request,response);
    }
}
